package com.shycloud.mido.organ.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.organ.api.dto.ActiveBatchDTO;
import com.shycloud.mido.organ.api.dto.ActiveByCodeDTO;
import com.shycloud.mido.organ.api.dto.JoyMasterDTO;
import com.shycloud.mido.organ.api.entity.*;
import com.shycloud.mido.organ.api.feign.RemoteMemberService;
import com.shycloud.mido.organ.api.vo.ProlongMasterVO;
import com.shycloud.mido.organ.mapper.MemberActivateMapper;
import com.shycloud.mido.organ.mapper.OptOrgMapper;
import com.shycloud.mido.organ.service.*;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.JDOMException;
import org.json.simple.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("/master/v2")
@Api(tags = "纠错大师模块")
public class MasterControllerV2 {

	private static Log logger = LogFactory.getLog(MasterControllerV2.class);

	/*******************************************************v1**********************************************************/
	private MemberActivateMapper memberActivateMapper;
	/** member 激活service */
	private MemberActivatedService memberActivatedService;
	/** 用户 service */
	private MemberService memberService;
	/** feign member Service */
	private RemoteMemberService remoteMemberService;
	/** 机构教师 service */
	private TeacherDetailedService teacherDetailedService;
	/** 学生 service */
	private StudentDetailedService studentDetailedService;
	/** 机构 service */
	private OrganizationService organizationService;

	@GetMapping("/generateCode")
	@ApiOperation("生成激活码")
	public R generateCode(Integer duration, Integer num, String comment, Integer comboId) {
		return memberActivatedService.generateCode(duration, num, comment, comboId, null, null);
	}

	/**
	 * 生成激活码(机构/运营商)
	 */
	@GetMapping("/genCode")
	@ApiOperation("生成激活码(机构/运营商)")
	public R genCode(Integer duration, Integer num, String comment, Integer comboId, Integer optId,
					 Integer orgId) {
		return memberActivatedService.generateCode(duration, num, comment, comboId, optId, orgId);
	}

	@Transactional
	@GetMapping("/allocate")
	public R allocate(Integer duration, Integer number, Integer optId, Integer orgId) {
		return new R<>(memberActivatedService
				.generateCode(duration, number, "来自总部分配", null, optId, orgId));
	}

	@GetMapping("/getCodePage")
	@ApiOperation("分页获取激活码")
	public R getCodePage(Page page, String code, String name, String duration, String comment) {
		return new R<>(memberActivateMapper.getCodePage(page, code, name, duration, comment));
	}

	/**
	 * 后台激活纠错大师
	 *
	 * @param memberId 会员ID
	 * @param code     激活码
	 * @return
	 */
	@GetMapping("/activateByCode")
	@ApiOperation("根据code激活硬件")
	public R activateByCode(String memberId, String code, String udid, String orgId, String optId,
							Integer duration) {
		return memberActivatedService.activateByCode(udid, code, memberId, orgId, optId);
	}

	/**
	 * 后台激活纠错大师
	 *
	 * @param memberId 会员ID
	 * @param code     激活码
	 * @return
	 */
	@GetMapping("/activateByCodeV2")
	@ApiOperation("根据code激活硬件-V2")
	public R activateByCodeV2(
			@ApiParam(value = "激活的开始日期，如未过期，则传到期时间") String startTime,
			@ApiParam(value = "用户memberId", required = true) String memberId,
			@ApiParam(value = "激活码", required = true) String code,
			@ApiParam(value = "UDID", required = true) String udid,
			@ApiParam(value = "机构ID", required = true) String orgId,
			@ApiParam(value = "运营商ID，只在运营商后台开通时使用") Integer optId,
			@ApiParam(value = "开通VIP时长，只在运营商后台开通时使用") Integer duration) {
		return memberActivatedService
				.activateByCode(startTime, udid, code, memberId, orgId, optId, duration);
	}

	/**
	 * 开通纠错大师体验
	 *
	 * @param udid
	 * @param memberId
	 * @param duration
	 * @param optId
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/activateByDuration")
	@ApiOperation("根据时长开通体验")
	public R activateByDuration(String udid, String memberId, int duration, String orgId,
								String optId) throws IOException, JDOMException {
		if (duration == 360) {
			duration = 365;
		}
		return memberActivatedService.activateByDuration(udid, memberId, duration, orgId, optId);
	}

	@PostMapping("/activateByDurationBatch")
	@ApiOperation("批量根据时长开通体验")
	@Transactional(rollbackFor = Exception.class)
	public R activateByDurationBatch(@RequestBody ActiveBatchDTO dto) {
		for (String memberId : dto.getMemberId()) {
			memberActivatedService.activateByDuration(
					dto.getUuid(), memberId, dto.getDuration(), dto.getOrgId(), dto.getOptId());
			MemberEntity member = memberService.getById(memberId);
			Map<String, Object> request = new HashMap<>();
			request.put("phone", member.getPhone());
			request.put("useTime", dto.getDuration());
			remoteMemberService.addVipMember(request);
		}
		return new R<>();
	}

	//延长体验时间
	@GetMapping("/delayHardwareVip")
	@ApiOperation("开通延期(硬件)")
	public R delayHardwareVip(String memberId, String endTime, Integer duration) {
		return memberActivatedService.delayHardwareVip(memberId, endTime, duration);
	}


	/**
	 * 后台管理系统 - 智能设备追溯列表
	 *
	 * @param page   分页参数
	 * @param udid   设备码
	 * @param orgId  机构 ID
	 * @param status 状态 0-未激活 1-已激活
	 * @param type   性质 租赁/销售
	 * @param name   激活用户
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/1/22 10:06
	 **/
	@GetMapping("/tracedBack")
	@ApiOperation("智能硬件追溯列表")
	public R tracedBack(Page page, String udid, String orgId, String status, String type,
						String name, Integer optId) {
		return new R<>(
				memberActivateMapper.tracedBack(page, udid, orgId, status, type, name, optId));
	}

	@GetMapping("/getActiveByCode")
	@ApiOperation("智能硬件激活列表")
	public R getActiveByCode(Page page, String phone, String orgId, String duration,
							 String leftDays, String startDate, String endDate) {
		return new R<>(memberActivateMapper
				.getActiveByCode(page, phone, orgId, duration, leftDays, startDate, endDate));
	}

	@GetMapping("/getActiveByDuration")
	@ApiOperation("智能硬件体验列表")
	public R getActiveByDuration(Page page, String phone, String orgId, String optId,
								 String duration, String leftDays, String startDate, String endDate, String dueStartDate,
								 String dueEndDate, String type) {
		IPage<ActiveByCodeDTO> result = memberActivateMapper
				.getActiveByDuration(page, phone, orgId, optId, duration, leftDays, startDate,
						endDate, dueStartDate, dueEndDate, type);
		//计算每条数据的到期时间和体验时长
		for (ActiveByCodeDTO item : result.getRecords()) {
			//根据memberId查询每个数据的详情
			List<ActiveByCodeDTO> list = memberActivateMapper
					.getActiveByMemberId(item.getMemberId(), type);
			//取第一次体验的开始时间为开始时间
			item.setStartDate(list.get(0).getStartDate());
			ActiveByCodeDTO theLast = list.get(list.size() - 1);
			item.setEndDate(theLast.getEndDate());
			//计算体验时长
			Integer durationTemp = 0;
			for (ActiveByCodeDTO itemOfList : list) {
				//1. 如果结束时间在今天之后 且 开始时间在今天之前
				if (itemOfList.getEndDateCompare().isAfter(LocalDateTime.now()) && itemOfList
						.getStartDateCompare().isBefore(LocalDateTime.now())) {
					Duration d = Duration
							.between(LocalDateTime.now(), itemOfList.getEndDateCompare());
					durationTemp += (int) d.toDays();
				} else {
					durationTemp += itemOfList.getDuration();
				}
			}
			item.setDuration(durationTemp);
		}
		return new R<>(result);
	}

	/**
	 * 是否是纠错大师
	 *
	 * @param phone 用户名
	 * @return {@link R}
	 */
	@GetMapping("/isMasterByPhone")
	@ApiOperation(value = "是否是纠错大师")
	public R isMasterByPhone(String phone) {

		List<MemberEntity> member = memberService.getMemberByPhone(phone);

		//用户不存在的情况
		if (member.size() == 0) {
			return new R(CommonConstants.FAIL, "用户不存在", false);
		}

		//用户已锁定的情况
		if ("9".equals(member.get(0).getLockFlag())) {
			return new R(CommonConstants.FAIL, "此用户已锁定", false);
		}

		Organization org = new Organization();

		//身份为教师
		if ("1".equals(member.get(0).getIsTeacher())) {
			//查询教师表，获取默认机构ID
			List<TeacherDetailedEntity> teacherDetaileds = teacherDetailedService
					.list(new QueryWrapper<TeacherDetailedEntity>()
							.eq("member_id", member.get(0).getId())
							.and(x -> x.eq("del_flag", "0"))
							.orderByAsc("create_time"));

			if (teacherDetaileds.size() == 0) {
				return new R(CommonConstants.FAIL, "教师信息获取失败，请联系管理员", false);
			} else {
				//获取机构信息
				org = organizationService.getById(teacherDetaileds.get(0).getOrgId());
			}

		}

		//身份为学生
		else {

			//查询教师表，获取默认机构ID
			List<StudentDetailedEntity> studentDetaileds = studentDetailedService
					.list(new QueryWrapper<StudentDetailedEntity>()
							.eq("member_id", member.get(0).getId())
							.and(x -> x.eq("del_flag", "0"))
							.orderByAsc("create_time"));

			if (studentDetaileds.size() > 0 && studentDetaileds.get(0).getOrgId() != 0) {
				//获取机构信息
				org = organizationService.getById(studentDetaileds.get(0).getOrgId());
			} else {
				//机构ID
				org.setId(0);
				//机构名
				org.setName("暂无机构");
			}
		}

		//新建返回结果集
		Map<String, Object> result = MapUtil.newHashMap();

		//Feign调用member模块获取用户详细信息
		R memberByPhone = remoteMemberService.getMemberByPhone(phone);
		//用户权限信息
		R master = checkMemberMaster(member.get(0).getId());

		//存入返回的结果集中
		result.put("memberDetail", memberByPhone.getData());
		result.put("masterDetail", master.getData());
		result.put("orgDetail", org);
		return new R(result);
	}

	/**
	 * 权限分配页面增加一条激活记录
	 *
	 * @param udid
	 * @param memberId
	 * @param duration
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/addActivation")
	public R addActivation(String udid, String memberId, int duration)
			throws IOException, JDOMException {
		return memberActivatedService.addActivation(udid, memberId, duration);
	}

	/**
	 * 获取权限开通页面已分配的激活列表
	 *
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/getAllocateActivationByPhone")
	public R getAllocateActivationByPhone(Page page, String phone, String code, String orgId,
										  String optId, String duration, String startDate, String endDate)
			throws IOException, JDOMException {
		return memberActivatedService
				.getAllocateActivation(page, phone, code, orgId, optId, duration, startDate,
						endDate);
	}

	/**
	 * 获取权限开通页面已分配的激活列表(运营商)
	 *
	 * @param page  分页参数
	 * @param optId 运营商ID
	 * @param phone 用户开通账号
	 * @param orgId 机构ID
	 * @param udid  UDID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/04/07 10:22
	 */
	@ApiOperation("获取权限开通页面已分配的激活列表(运营商)")
	@GetMapping("/getAllocateActivationByOpt")
	public R<IPage<JoyMasterDTO>> getAllocateActivationByOptr(Page page, String phone, String udid,
															  Integer optId, Integer orgId) {
		return memberActivatedService.getAllocateActivationByOpt(page, phone, udid, orgId, optId);
	}

	/**
	 * 获取所有激活记录
	 *
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/getAllActivation")
	public R getAllActivation(Page page, String duration, String code, String phone)
			throws IOException, JDOMException {
		return memberActivatedService.getAllActivation(page, phone, code, duration);
	}

	/**
	 * 设定机构(包括工作室)临时激活次数分配
	 *
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@PostMapping("/setCountByOrg")
	public R setOrgActivationCount(@RequestBody Map<Object, Object> paramMap)
			throws IOException, JDOMException {
		Integer orgId = (Integer) paramMap.get("orgId");
		String updatePerson = (String) paramMap.get("updatePerson");
		paramMap.remove("orgId");
		paramMap.remove("updatePerson");
		return memberActivatedService
				.setActivationCountByOrg(String.valueOf(orgId), updatePerson, paramMap);
	}

	/**
	 * 设定运营商临时激活次数分配
	 *
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	//Dreprecated 运营商的去Opter的OperateController分配
	@PostMapping("/setCountByOptr")
	public R setOptrActivationCount(@RequestBody Map<Object, Object> paramMap)
			throws IOException, JDOMException {
		String optrId = String.valueOf((Integer) paramMap.get("optrId"));
		paramMap.remove("optrId");
		logger.info("optrId: " + optrId);
		logger.info("durationMap: " + JSONObject.toJSONString(paramMap));
		R r = memberActivatedService.setActivationCountByOptr(optrId, paramMap);
		return r;
	}

	/**
	 * 查看分配记录
	 *
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/getOrgCountRecord")
	public R getOrgCountRecord(String orgId) throws IOException, JDOMException {
		return memberActivatedService.getOrgCountRecord(orgId);
	}

	/**
	 * 查看分配记录
	 *
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/getCountRecByStudio")
	public R getStudioCountRecord(String orgId) throws IOException, JDOMException {
		return memberActivatedService.getStudioCountRecord(orgId);
	}

	/**
	 * 查看分配记录
	 *
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	//Dreprecated 运营商的分配记录去Opter的OperateController查看
	@GetMapping("/getOptrCountRecord")
	public R getOptrCountRecord(String optrId) throws IOException, JDOMException {
		return memberActivatedService.getOptrCountRecord(optrId);
	}

	/**
	 * app端激活纠错大师
	 *
	 * @param map
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/18 9:47
	 */
	@ApiOperation("app端激活纠错大师")
	@PostMapping("addActivationApp")
	public R addActivationForApp(@RequestBody Map<String, String> map) {

		//设备编号 udid
		String udid = map.get("udid");
		//激活码
		String actvCode = map.get("code");

		return memberActivatedService
				.addActivationForApp(udid, actvCode, SecurityUtils.getMember().getId());

	}

	/**
	 * H5 端激活纠错大师
	 *
	 * @param map
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/18 9:47
	 */
	@ApiOperation("app端激活纠错大师")
	@PostMapping("addActivationH5")
	public R addActivationH5(@RequestBody Map<String, String> map) {

		//设备编号 udid
		String udid = map.get("udid");
		//激活码
		String actvCode = map.get("actCode");
		//用户ID
		String memberId = map.get("memberId");

		return memberActivatedService.addActivationForApp(udid, actvCode, memberId);

	}

	/**
	 * 检查 udid 状态
	 *
	 * @param udid
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/1/19 17:11
	 **/
	@GetMapping("checkUdid")
	public R checkUdid(String udid) {

		// 处理 UDID
		String replace = udid.replace("http://shop.joymido.com/activation/?udid=", "");

		if (memberActivatedService.checkUdid(replace)) {
			return new R(true);
		} else {
			return new R(false, "二维码无效，请重新扫码！");
		}

	}

	/**
	 * 查看登录用户是否激活纠错大师
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/18 13:52
	 */
	@GetMapping("checkMemberMaster")
	@ApiOperation("查看登录用户是否激活纠错大师")
	public R<Map<String, Object>> checkMemberMaster(String memberId) {

		//创建返回用结果集
		Map<String, Object> resultMap = MapUtil.newHashMap();

		if (StringUtils.isEmpty(memberId)) {
			if (SecurityUtils.getMember() == null) {
				resultMap.put("status", 0);
				return new R(CommonConstants.FAIL, "用户信息获取失败", false);
			} else {
				memberId = SecurityUtils.getMember().getId();
			}
		}

		//根据 memberid 查询用户激活信息
		List<MemberActivateEntity> memberActivateEntityList = memberActivatedService
				.list(new QueryWrapper<MemberActivateEntity>()
						.eq("member_id", memberId)
						.orderByAsc("start_time"));

		//如果已经开通
		if (memberActivateEntityList.size() > 0) {

			resultMap.put("status", 1);
			//设备编号
			resultMap.put("udid", memberActivateEntityList.get(0).getUdid());
			//开始时间
			DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			resultMap.put("startTime", memberActivateEntityList.get(0).getStartTime().format(dtf3));
			//激活码
			resultMap.put("code", memberActivateEntityList.get(memberActivateEntityList.size() - 1)
					.getActvCode());
			//到期时间
			int duration = 0;

			LocalDateTime endTime = memberActivateEntityList.get(0).getStartTime()
					.plusDays(duration);

			for (MemberActivateEntity memberActivateEntity : memberActivateEntityList) {

				//如果有一条到期时间为永久，直接返回
				if (memberActivateEntity.getDuration() == 0) {
					resultMap.put("endTime", 0);
					return new R<>(resultMap);
				} else {
					duration += memberActivateEntity.getDuration();
					//循环取到期时间最后的
					if (endTime.isAfter(memberActivateEntity.getStartTime()
							.plusDays(memberActivateEntity.getDuration()))) {

					} else {
						endTime = memberActivateEntity.getStartTime()
								.plusDays(memberActivateEntity.getDuration());
					}
				}

			}

			if (endTime.isBefore(LocalDateTime.now())) {
				resultMap.put("status", 2);
			}

			resultMap.put("endTime", endTime.format(dtf3));
		}

		//不是纠错大师
		else {
			resultMap.put("status", 0);
		}

		return new R<>(resultMap);
	}

	/**
	 * 查看登录用户是否激活纠错大师
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2021/3/30 09:54
	 */
	@GetMapping("checkMemberMasterFast")
	@ApiOperation("查看用户是否激活纠错大师 Feign 专用")
	public String checkMemberMasterFast(String memberId) {

		//根据 memberid 查询用户激活信息
		List<MemberActivateEntity> memberActivateEntityList = memberActivatedService
				.list(new QueryWrapper<MemberActivateEntity>()
						.eq("member_id", memberId)
						.orderByAsc("start_time"));

		String res = "0";
		//如果已经开通
		if (memberActivateEntityList.size() > 0) {

			res = "1";

			//到期时间
			int duration = 0;

			LocalDateTime endTime = memberActivateEntityList.get(0).getStartTime()
					.plusDays(duration);

			for (MemberActivateEntity memberActivateEntity : memberActivateEntityList) {

				//如果有一条到期时间为永久，直接返回
				if (memberActivateEntity.getDuration() == 0) {
					return "1";
				} else {
					duration += memberActivateEntity.getDuration();
					//循环取到期时间最后的
					if (endTime.isAfter(memberActivateEntity.getStartTime()
							.plusDays(memberActivateEntity.getDuration()))) {

					} else {
						endTime = memberActivateEntity.getStartTime()
								.plusDays(memberActivateEntity.getDuration());
					}
				}

			}

			if (endTime.isBefore(LocalDateTime.now())) {
				res = "0";
			}

		}
		//不是纠错大师
		else {
			res = "0";
		}
		return res;
	}

	/**
	 * 续期纠错大师
	 *
	 * @param prolongMasterVO
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/6/18 15:26
	 */
	@PostMapping("prolongMaster")
	@ApiOperation("续期纠错大师")
	public R prolongMaster(@RequestBody ProlongMasterVO prolongMasterVO) {

		//设备编号 udid
		String udid = prolongMasterVO.getUdid();
		//激活码
		String actvCode = prolongMasterVO.getCode();
		//开始时间
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime startTime = LocalDateTime
				.parse(prolongMasterVO.getEndTime() + " 00:00:00", dateTimeFormatter);

		return memberActivatedService
				.prolongMaster(udid, actvCode, SecurityUtils.getMember().getId(), startTime);
	}

	@GetMapping("isMaster")
	public R isMaster(String memberId) {
		return memberActivatedService.isMaster(memberId);
	}

	/**
	 * 获取纠错大师到期日期 （feign专用）
	 *
	 * @param memberId
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/12/8 11:36
	 **/
	@GetMapping("getMasterEndTime")
	public String getMasterEndTime(String memberId) {

		//根据 memberid 查询用户激活信息
		List<MemberActivateEntity> memberActivateEntityList = memberActivatedService
				.list(new QueryWrapper<MemberActivateEntity>()
						.eq("member_id", memberId)
						.orderByAsc("start_time"));

		//如果已经开通
		if (memberActivateEntityList.size() > 0) {

			//到期时间
			int duration = 0;
			for (MemberActivateEntity memberActivateEntity : memberActivateEntityList) {
				//如果有一条到期时间为永久，直接返回
				if (memberActivateEntity.getDuration() == 0) {
					return "2046-12-31";
				} else {
					duration += memberActivateEntity.getDuration();
				}
			}

			LocalDateTime endTime = memberActivateEntityList.get(0).getStartTime()
					.plusDays(duration);

			return endTime.toString();

		}
		return null;
	}

	/**
	 * 小程序端后台管理系统开通硬件权限
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/activateByDurationMini")
	@ApiOperation("小程序端后台管理系统开通硬件权限")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "udid", value = "设备码", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "busiType", value = "业务类型（1-销售 2-出租 3-体验）", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "durationType", value = "时长类型(1-年,2-月,3-日)", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "durationTypeValue", value = "时长类型值", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "remark", value = "备注", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "optId", value = "运营商ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "orgId", value = "机构ID（目前版本不传）", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "distId", value = "经销商ID（0706新版本）", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "specialType", value = "特殊类型，0 斑马遗留码 1 Mido新码 2 管理后台权限开通分配 3 合作商租赁押金模式码", paramType = "query", dataType = "int"),

	})
	public R<LocalDateTime> activateByDurationMini(String udid, String busiType,
												   String durationType, Integer durationTypeValue, String remark, Integer optId,
												   Integer orgId, Integer distId, Integer specialType) throws IOException, JDOMException {
		return new R(memberActivatedService
				.activateByDurationMini(udid, busiType, durationType, durationTypeValue, remark,
						optId, orgId, distId, specialType));
	}

	/**
	 * 小程序端后台管理系统开通硬件权限
	 *
	 * @return com.shycloud.mido.common.core.util.R
	 * @throws IOException
	 * @throws JDOMException
	 */
	@GetMapping("/activateByDurationMiniSale")
	@ApiOperation("小程序端后台管理系统开通硬件权限")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "udid", value = "设备码", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "busiType", value = "业务类型（1-销售 2-出租 3-体验）", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "durationType", value = "时长类型(1-年,2-月,3-日)", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "durationTypeValue", value = "时长类型值", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "remark", value = "备注", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "optId", value = "运营商ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "orgId", value = "机构ID（目前版本不传）", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "distId", value = "经销商ID（0706新版本）", paramType = "query", dataType = "int"),

	})
	public R<LocalDateTime> activateByDurationMiniSale(String udid, String busiType,
													   String durationType, Integer durationTypeValue, String remark, Integer optId,
													   Integer orgId, Integer distId) throws IOException, JDOMException {
		return new R(memberActivatedService
				.activateByDurationMiniSale(udid, busiType, durationType, durationTypeValue, remark,
						optId, orgId, distId));
	}

	/**
	 * 根据 orderNo 延长纠错大师权限
	 *
	 * @param
	 * @return
	 * @author nianhua.jiang
	 * @date 2021/11/2 16:26
	 */
	@GetMapping("prolongMasterFeign")
	public R prolongMasterNoFeign(String udid, Integer duration) {
		MemberActivateEntity memberActivateEntity = memberActivateMapper.selectOne(new QueryWrapper<MemberActivateEntity>()
				.eq("udid", udid));
		memberActivateEntity.setStartTime(LocalDateTime.now());
		memberActivateEntity.setDuration(memberActivateEntity.getDuration() + duration);
		return new R(memberActivateMapper.updateById(memberActivateEntity));
	}

	@GetMapping("updPreStorageCount")
	public R updPreStorageCount(Integer orgId, Integer preStorageCount) {
		return new R(organizationService.updPreStorageCount(orgId, preStorageCount));
	}
	
	@GetMapping("checkAndUpdPreStorageCount")
	public R<Boolean> checkAndUpdPreStorageCount(Integer orgId, Integer preStorageCount) {
		return new R<>(organizationService.checkAndUpdPreStorageCount(orgId, preStorageCount));
	}

}
